const util = require('../../utils/util.js');

Page({
  data: {
    showOverlay: false,
    showOverlay2: false,
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    userInfo: {}, //用户数据
    flowerPotsCount: 0, // 花盆的数量
    flowerPots: [], // 用于存储花盆图片的数组
    userUID: null, // 用户UID
    NowRecordID: null, //当前点击的花盆ID
    NowFlowerID: null, //当前点击的花ID
    FlowerExp: 0, //当前花的经验值
    FlowerFullExp: 0, //当前花升级所需经验阈值
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    // 登录验证
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
    const appInstance = getApp();
    // 检查全局数据中是否已经有用户信息
    if (appInstance.globalData.userInfo) {
      this.setData({
        userInfo: appInstance.globalData.userInfo,
        hasUserInfo: true
      });
    }
    // 检查全局数据中是否有用户信息
    const userInfo = getApp()
      .globalData.userInfo;
    console.log('用户资料:', userInfo)
    if (userInfo && userInfo.username && userInfo.useravatar) {
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      });
    }
    // 获取用户UID
    util.request(getApp().globalData.requestUrl + 'users/GetUID', 'GET')
      .then(uidRes => {
        if (uidRes.code === 200) {
          const uid = uidRes.data;
          this.data.userUID = uid;
          // 获取花朵数量和 RecordID
          return util.request(`http://localhost:3000/garden/GetFlowerQuantityAndRecordIDs?UID=${uid}`, 'GET');
        } else {
          throw new Error(`获取用户UID失败：${uidRes.message}`);
        }
      })
      .then(res => {
        if (res.code === 200) {
          const flowerCount = res.data.flowerCount;
          const recordIDs = res.data.recordIDs;
          this.setData({
            flowerPotsCount: flowerCount
          });
          // 构建初始花盆数据
          const flowerPots = recordIDs.map(recordId => {
            return {
              id: recordId,
              flowerId: '',
              recordId: recordId,
              src: ''
            };
          });
          this.setData({
            flowerPots: flowerPots
          });
          this.getFlowerIds(recordIDs);
        } else {
          throw new Error(`获取花朵ID与数量出错：${res.message}`);
        }
      })
      .catch(error => {
        console.error('请求失败：', error);
      });
  },


  /**
   * 获取花朵ID
   * @param {Array} recordIDs - 花盆记录ID数组
   */
  getFlowerIds: function (recordIDs) {
    recordIDs.forEach((recordId) => {
      // 从缓存中获取花朵ID
      wx.getStorage({
        key: recordId.toString(),
        success: (res) => {
          // 如果存在，用缓存数据
          this.handleFlowerIdResponse(recordId, res.data);
        },
        fail: () => {
          // 如果不存在，从后端获取花朵ID
          util.request(`http://localhost:3000/garden/GetFlowerID?RecordID=${recordId}`, 'GET')
            .then((res) => {
              if (res.code === 200) {
                const flowerId = res.data;
                // 存入缓存
                wx.setStorage({
                  key: recordId.toString(),
                  data: flowerId,
                  success: () => {
                    this.handleFlowerIdResponse(recordId, flowerId);
                  },
                  fail: (error) => {
                    console.error(`存储花朵ID到本地缓存失败，RecordID：${recordId}:`, error);
                  }
                });
              } else {
                console.error(`获取花朵ID出错，RecordID：${recordId}:`, res.message);
              }
            })
            .catch((error) => {
              console.error(`获取花朵ID出错，RecordID：${recordId}:`, error);
            });
        }
      });
    });
  },

  /**
   * 处理花朵ID的响应
   * @param {number} recordId - 花盆记录ID
   * @param {string} flowerId - 花朵ID
   */
  handleFlowerIdResponse: function (recordId, flowerId) {
    // 更新花盆的花朵ID
    const updatedPots = this.data.flowerPots.map((pot) => {
      if (pot.recordId === recordId) {
        return {
          ...pot,
          flowerId: flowerId
        };
      }
      return pot;
    });
    this.setData({
      flowerPots: updatedPots
    });
    this.getFlowerPhotos(flowerId);
  },

  /**
   * 根据花朵ID获取花朵图片URL
   * @param {string} flowerId - 花朵ID
   */
  getFlowerPhotos: function (flowerId) {
    // 先看缓存中是否有对应花朵图片URL
    const cachedPhotoUrl = wx.getStorageSync(`flowerPhoto_${flowerId}`);
    if (cachedPhotoUrl) {
      // 更新花盆的花朵图片URL
      const updatedPots = this.data.flowerPots.map((pot) => {
        if (pot.flowerId === flowerId) {
          return {
            ...pot,
            src: cachedPhotoUrl
          };
        }
        return pot;
      });
      this.setData({
        flowerPots: updatedPots
      });
      return; // 结束函数，不再执行后续的网络请求
    }

    // 如果没有，向后段获取花朵图片URL
    util.request(`http://localhost:3000/flower/GetFlowerPhoto?FlowerID=${flowerId}`, 'GET')
      .then((res) => {
        if (res.code === 200) {
          const flowerPhotoUrl = res.data;
          // 更新缓存中的花朵图片URL
          wx.setStorageSync(`flowerPhoto_${flowerId}`, flowerPhotoUrl);

          // 更新花盆的花朵图片URL
          const updatedPots = this.data.flowerPots.map((pot) => {
            if (pot.flowerId === flowerId) {
              return {
                ...pot,
                src: flowerPhotoUrl
              };
            }
            return pot;
          });
          this.setData({
            flowerPots: updatedPots
          });
        } else {
          console.error(`获取花朵图片出错，FlowerID：${flowerId}:`, res.message);
        }
      })
      .catch((error) => {
        console.error(`获取花朵图片出错，FlowerID：${flowerId}:`, error);
      });
  },

  /**
   * 点击种子按钮触发的事件
   */
  click_seed() {
    this.setData({
      showOverlay2: true
    })
  },

  /**
   * 处理花盆点击事件
   * @param {object} e - 事件对象，包含当前点击元素的数据集合
   */
  handlePotTap: function (e) {
    this.setData({
      showOverlay: true
    })
    const dataset = e.currentTarget.dataset;
    this.data.NowRecordID = dataset.recordid;
    const recordId = dataset.recordid;
    this.data.NowFlowerID = dataset.flowerid;
    const flowerId = dataset.flowerid;
    console.log('点击了花盆，recordId:', this.data.NowRecordID, '点击了花盆，flowerId:', this.data.NowFlowerID);
    this.GetExp(recordId);
    this.GetFullExp(flowerId);
  },

  /**
   * 使用种子
   */
  use_seed() {
    this.useResource('seed', () => {
      util.request(getApp().globalData.requestUrl + 'garden/AddFlower', 'POST', {
          UID: this.data.userUID
        })
        .then((res) => {
          if (res.code === 200) {
            wx.redirectTo({
              url: '/pages/garden/garden'
            });
          } else {
            console.error('种子种植失败:', res.message);
          }
        })
        .catch((error) => {
          console.error('种子种植失败:', error);
        });
    });
  },

  /**
   * 使用水
   */
  use_water() {
    this.useResource('water', () => {
      this.updateFlowerExp(this.data.FlowerExp + 3);
    });
  },

  /**
   * 使用化肥
   */
  use_fertilizer() {
    this.useResource('fertilizer', () => {
      this.updateFlowerExp(this.data.FlowerExp + 7);
    });
  },

  /**
   * 使用资源的通用方法
   * @param {string} resourceType - 资源类型，
   * @param {function} successCallback - 成功回调函数
   */
  useResource(resourceType, successCallback) {
    // 调用 hss 组件的使用资源
    const hssComponent = this.selectComponent('#hss');
    if (hssComponent) {
      const purchaseResult = hssComponent.useWay(resourceType);
      if (purchaseResult) {
        if (successCallback) {
          successCallback(); // 调用成功回调函数
        }
      } else {
        console.error(`使用${resourceType}失败`);
      }
    } else {
      console.error(`无法找到 hss 组件实例.`);
    }
    this.hideOverlay();
  },


  /**
   * 隐藏覆盖层
   */
  hideOverlay: function () {
    this.setData({
      showOverlay: false,
      showOverlay2: false,
    });
  },

  /**
   * 获取用户信息的方法
   */
  getUserProfile: function () {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        const userInfo = res.userInfo;
        this.setData({
          userInfo,
          hasUserInfo: true
        });
        this.saveUserInfo(userInfo); // 保存用户信息到全局和缓存
      }
    });
  },

  // 选择头像
  onChooseAvatar: function (e) {
    const avatarUrl = e.detail.avatarUrl;
    const userInfo = this.data.userInfo;
    getApp()
      .uploadImage(avatarUrl, getApp()
        .globalData.userInfo.username)
      .then((newAvatarUrl) => {
        console.log('新头像:', newAvatarUrl);
        userInfo.useravatar = newAvatarUrl;
        this.setData({
          userInfo: userInfo
        });
        getApp()
          .saveUserInfo(userInfo); // 更新用户信息
        this.updateUserPhoto(newAvatarUrl);
        console.log('更新头像:', newAvatarUrl);
      })
      .catch((error) => {
        console.error('上传头像失败:', error);
        // 处理上传失败的情况，例如提示用户或者进行其他操作
      });
  },

  // 输入昵称
  onChooseNickname: function (e) {
    const nickname = e.detail.value;
    const userInfo = this.data.userInfo;
    userInfo.username = nickname; // 注意微信接口返回的字段是nickName而不是nickname
    this.setData({
      userInfo
    });
    getApp()
      .saveUserInfo(userInfo); // 更新全局和缓存中的用户信息
    this.updateUserName(nickname);
    console.log('更新昵称:', nickname)
  },

  // 更新用户昵称
  updateUserName: function (newName) {
    util.request(getApp().globalData.requestUrl + 'users/UpdateName', 'POST', {
        newData: newName
      })
      .then((res) => {
        if (res.code === 200) {
          console.log('用户昵称更新成功');
          // 可以根据需要进行额外的操作
        } else {
          console.error('更新用户昵称失败:', res.message);
        }
      })
      .catch((error) => {
        console.error('更新用户昵称失败:', error);
      });
  },


  // 更新用户头像
  updateUserPhoto: function (newPhotoUrl) {
    util.request(getApp().globalData.requestUrl + 'users/UpdatePhoto', 'POST', {
        newData: newPhotoUrl
      })
      .then((res) => {
        if (res.code === 200) {
          console.log('用户头像更新成功');
          // 在这里可以根据需要进行额外的操作
        } else {
          console.error('更新用户头像失败:', res.message);
        }
      })
      .catch((error) => {
        console.error('更新用户头像失败:', error);
      });
  },

  // 获取当前点击花朵的经验
  GetExp: function (recordId) {
    util.request(getApp().globalData.requestUrl + 'garden/GetFlowerExp', 'GET', {
        RecordID: recordId
      })
      .then(res => {
        this.setData({
          FlowerExp: res.data
        });
        console.log('成功获取当前花朵经验:', this.data.FlowerExp);
      })
      .catch(error => {
        console.error('获取当前花朵经验失败:', error);
      });
  },

  // 获取当前点击花朵升级所需经验
  GetFullExp: function (flowerId) {
    util.request(getApp().globalData.requestUrl + 'flower/GetFlowerFullExp', 'GET', {
        FlowerID: flowerId
      })
      .then(res => {
        this.setData({
          FlowerFullExp: res.data
        });
        console.log('成功获取当前花朵升级所需经验:', this.data.FlowerFullExp);
      })
      .catch(error => {
        console.error('获取当前花朵升级所需经验失败:', error);
      });
  },

  // 更新花朵经验值的接口请求函数
  updateFlowerExp: function (expToAdd) {
    var self = this;
    util.request(getApp().globalData.requestUrl + 'garden/UpdateFlowerExp', 'POST', {
        RecordID: self.data.NowRecordID,
        newData: expToAdd
      })
      .then(res => {
        console.log('更新花朵经验值成功:', res.data);
        const FlowerExp = res.data;
        const FlowerFullExp = self.data.FlowerFullExp;
        console.log('当前经验:', FlowerExp, '升级经验:', FlowerFullExp);
        if (FlowerExp >= FlowerFullExp) {
          wx.setStorageSync(self.data.NowRecordID, self.data.NowFlowerID + 1);
          util.request(getApp().globalData.requestUrl + 'garden/UpdateFlowerExp', 'POST', {
            RecordID: self.data.NowRecordID,
            newData: 0
          })
          return util.request(getApp().globalData.requestUrl + 'garden/UpdateFlowerID', 'POST', {
            RecordID: self.data.NowRecordID,
            newData: self.data.NowFlowerID + 1
          });
        }
      })
      .then(res => {
        if (res) {
          console.log('花朵升级了');
          wx.redirectTo({
            url: '/pages/garden/garden'
          });
        }
      })
      .catch(error => {
        console.error('花朵升级失败:', error);
      });
  },
});